package cn.gjxblog.aop.proxy.jdk;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;

/**
 * jdk创建代理类的示例
 */
public class JdkProxy {

    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        // 改变JVM参数，使其能够保存动态生成的代理类
        System.setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles","true");

        UserServiceImpl userService = new UserServiceImpl();
        // 实现一个InvocationHandler
        MyInterceptor myInterceptor = new MyInterceptor(userService);
//        method1(myInterceptor);

        method2(myInterceptor);
    }

    /**
     * 方式一
     */
    private static void method1(InvocationHandler invocationHandler) {
        UserService userService1 = (UserService) Proxy.newProxyInstance(JdkProxy.class.getClassLoader(), new Class[]{UserService.class}, invocationHandler);
        userService1.getUser(1);

    }

    /**
     * 方式二
     * 方式二是方式一的原理
     */
    private static void method2(InvocationHandler invocationHandler) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        // 生成代理类
        Class<?> proxyClass = Proxy.getProxyClass(JdkProxy.class.getClassLoader(), UserService.class);
        // 获取代理类的构造方法
        Constructor<?> constructor = proxyClass.getConstructor(InvocationHandler.class);
        // 创建实例
        UserService userService = (UserService) constructor.newInstance(invocationHandler);
        userService.getUser(1);
        System.out.println(userService.getClass());
//        userService.toString();

    }
}
